<template>
  <div>
    <el-dialog :visible.sync="dialogShow" width="90%" :close-on-click-modal="false" :close-on-press-escape="false">
      <div slot="title">
        <div>
          <span class="font-size-18 font-weight-700">抵扣</span>
          <span class="font-size-14 padding-left-20">可抵扣金额{{ (currentBill.remainingAmount || 0) | fmoneyThousand }}元</span>
        </div>
      </div>

      <template v-if="writeOffList.length > 0">
        <div v-for="(item, index) in writeOffList" :key="item.guid" class="padding-bottom-10 fill-box relative-box" :class="index < writeOffList.length - 1 ? 'border-b-line margin-bottom-30' : ''">
          <form-common :filed-list="item.filedList" :ref="`writeOff${index}`" @selectChange="selectChange"></form-common>
          <el-button class="delete-btn" type="danger" size="mini" @click="deleteWriteOff(index)">删除</el-button>
        </div>
      </template>
      <el-empty v-else description="暂无数据"></el-empty>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" class="el-button-reset" @click="addWriteOf">添加核销信息</el-button>
        <el-button type="primary" size="mini" @click="saveWriteOff">确 认</el-button>
        <el-button size="mini" @click="dialogShow = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { deductionFiledList } from '../../../assets/form';
  import formCommon from '@g/components/form/formCommon.vue';
  import { apiDepositWriteOff } from '../../../api/depositManage';
  import { requestTips, guid, formDataDate, accAdd } from '@js/utils';
  import { apiWriteOffBillImport, apiGetChargeListByContract, apiWriteOffExport } from '../../../api/billManage';

  export default {
    name: 'deduction',
    props: {
      currentBill: {
        type: Object,
        default: () => {
          return {};
        },
      },
      options: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },

    data() {
      return {
        dialogShow: false,
        writeOffList: [],
      };
    },

    methods: {
      init() {
        this.writeOffList = [];
        this.setOptions();
        this.dialogShow = true;
        let filedList = this.lodash.cloneDeep(deductionFiledList);
        this.writeOffList.push({
          guid: guid(),
          filedList: filedList,
        });
      },

      //添加抵扣信息
      addWriteOf() {
        if (!this.currentBill.remainingAmount || this.currentBill.remainingAmount == 0) {
          this.$message.warning('暂无可抵扣金额');
          return;
        }
        let filedList = this.lodash.cloneDeep(deductionFiledList);
        this.writeOffList.push({
          guid: guid(),
          filedList: filedList,
        });
      },

      //删除抵扣
      deleteWriteOff(index) {
        this.writeOffList.splice(index, 1);
      },

      async saveWriteOff() {
        if (!this.currentBill.remainingAmount || this.currentBill.remainingAmount == 0) {
          this.$message.warning('暂无可抵扣金额');
          return;
        }
        
        let list = [];
        let allAmount = 0;
        if (this.writeOffList.length == 0) {
          this.$message.warning('请添加抵扣信息!');
          return;
        }

        this.writeOffList.forEach((item, index) => {
          let formName = 'writeOff' + index;
          let model = this.$refs[formName][0].validateForm();
          list.push(model);
        });

        if (list.indexOf(false) > -1) {
          return;
        }

        list.forEach(item => {
          allAmount = accAdd(allAmount, item.writeOffAmount);
        });

        if (allAmount > this.currentBill.remainingAmount) {
          this.$message.warning('核销金额大于可核销金额！');
          return;
        }

        let res = await apiDepositWriteOff({ writeOffList: list, depositBillKey: this.currentBill.primaryKey });
        requestTips(res, () => {
          this.dialogShow = false;
          this.$emit("confirmDeduction")
        });
      },

      //表单事件
      async selectChange(data) {
        //选账单
        if (data.filedName == 'bizType' || data.filedName == 'contractCode' || data.filedName == 'chargeItemCode') {
          if (data.model.projectKey && data.model.contractCode && data.model.bizType && data.model.chargeItemCode) {
            let params = {
              projectKey: data.model.projectKey,
              contractCode: data.model.contractCode,
              bizType: data.model.bizType,
              chargeItemCode: data.model.chargeItemCode,
              paymentStatusList: [1, 2, 3],
            };
            let res = await apiWriteOffBillImport(params);
            res.rows.forEach(item => {
              item.name = formDataDate(item.cycleStartTime) + '至' + formDataDate(item.cycleEndTime) + '账单';
            });
            data.cbList('billKey', res.rows || []);
          }
          if (data.filedName == 'contractCode') {
            let res = await apiGetChargeListByContract({ contractCode: data.filedVal });
            data.cbList('chargeItemCode', res.rows || []); //费用所属
          }
        }
        if (data.filedName == 'billKey') {
          let target = data.formItem.optionList.find(item => item.primaryKey == data.filedVal);
          data.cb('shouldAmount', target.amountReceivable);
          data.cb('alreadyAmount', target.amountReceived);
        }
      },

      //下拉框数据源
      setOptions() {
        console.log(this.options);
        deductionFiledList.forEach(item => {
          if (item.bindFieldName == 'projectKey') {
            item.optionList = this.options.projectList;
            item.bindFieldVal = this.currentBill.projectKey;
          }
          if (item.bindFieldName == 'bizType') {
            item.optionList = this.options.costTypeList;
          }
          if (item.bindFieldName == 'contractCode') {
            item.optionList = this.options.contractList;
          }
        });
      },
    },

    created() {},

    mounted() {},

    components: { formCommon },
  };
</script>

<style lang="scss" scoped>
  .delete-btn {
    position: absolute;
    bottom: 29px;
    right: 0;
  }
</style>
